const inquirer = require('inquirer')
const fs = require('fs')
const { resolve } = require('path')
const exec = require('child_process').exec

const log = console.log
const publishPackage = './publish/package.json'
const publishComponentsDir = './publish/components/'
const componentsDir = './src/components/'
const packageJson = require(publishPackage)

const removeDir = (path) => {
    let files = [];
    if (fs.existsSync(path)) {
      files = fs.readdirSync(path);
      files.forEach((file) => {
        const curPath = path + "/" + file;
        if (fs.statSync(curPath).isDirectory()) { // recurse
          removeDir(curPath);
        } else { // delete file
          fs.unlinkSync(curPath);
        }
      });
      fs.rmdirSync(path);
    }
};

const copyDir = (copyPath, targetPath) => {
  if (!fs.existsSync(targetPath)) fs.mkdirSync(targetPath);
  exec(`Xcopy ${resolve(copyPath)} ${resolve(targetPath)} /s`)
}

log('发布npm包')
inquirer.prompt([
  {
    type: "input",
    name: "version",
    message: `package version(current:${packageJson.version}):`,
    validate : val => !!val
  }
])
  .then(async ({ version }) => {
    removeDir(publishComponentsDir)
    copyDir(componentsDir, publishComponentsDir)
    packageJson.version = version
    const writeFs = fs.writeFileSync(publishPackage, JSON.stringify(packageJson))
    if (writeFs) return Promise.reject(writeFs)
  }).catch(err => {
    log(err)
  })
